package com.demo.delivery.sqlite;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.demo.delivery.entity.Food;

import java.util.ArrayList;
import java.util.List;

public class FoodCartBusiness {

    /**
     * 添加购物车中的食物
     */
    public static BusinessResult<Food> add(Food food, Integer userId) {
        if (userId == null) {
            return new BusinessResult<>(false, "用户id不能为空", null);
        }
        BusinessResult<Food> queryByNameAndUserId = queryByNameAndUserId(food.getName(), userId);
        if (queryByNameAndUserId.isSuccess()) {
            Food result = queryByNameAndUserId.getData();
            result.setCount(result.getCount() + 1);
            BusinessResult<Food> update = update(result);
            if (update.isSuccess()) {
                return new BusinessResult<>(true, "添加成功", result);
            } else {
                return new BusinessResult<>(false, "添加失败", null);
            }
        } else {
            food.setCount(1);
            food.setUserId(userId);
            return insert(food);
        }
    }

    /**
     * 减少购物车中的食物
     */
    public static BusinessResult<Food> minus(Food food, Integer userId) {
        if (food.getUserId() == null) {
            return new BusinessResult<>(false, "用户id不能为空", null);
        }
        BusinessResult<Food> queryByNameAndUserId = queryByNameAndUserId(food.getName(), userId);
        if (queryByNameAndUserId.isSuccess()) {
            Food result = queryByNameAndUserId.getData();
            if (result.getCount() > 1) {
                result.setCount(result.getCount() - 1);
                BusinessResult<Food> update = update(result);
                if (update.isSuccess()) {
                    return new BusinessResult<>(true, "减少成功", result);
                } else {
                    return new BusinessResult<>(false, "减少失败", null);
                }
            } else {
                return deleteByNameAndUserId(food.getName(), userId);
            }
        } else {
            return new BusinessResult<>(false, "食物不存在", null);
        }
    }

    /**
     * 根据食物名和用户id删除
     */
    private static BusinessResult<Food> deleteByNameAndUserId(String name, Integer userId) {
        if (TextUtils.isEmpty(name)) {
            return new BusinessResult<>(false, "食物名不能为空", null);
        }
        if (userId == null) {
            return new BusinessResult<>(false, "用户id不能为空", null);
        }
        DatabaseHelper instance = DatabaseHelper.getInstance();
        SQLiteDatabase db = instance.getWritableDatabase();
        String sql = "DELETE FROM food WHERE name=? AND user_id=?";
        String[] args = new String[]{name, String.valueOf(userId)};
        db.execSQL(sql, args);
        return new BusinessResult<>(true, "删除成功", null);
    }

    /**
     * 添加
     */
    private static BusinessResult<Food> insert(Food food) {
        if (food.getUserId() == null) {
            return new BusinessResult<>(false, "用户id不能为空", null);
        }
        if (TextUtils.isEmpty(food.getName())) {
            return new BusinessResult<>(false, "食物名不能为空", null);
        }
        DatabaseHelper instance = DatabaseHelper.getInstance();
        SQLiteDatabase db = instance.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("user_id", food.getUserId());
        values.put("name", food.getName());
        values.put("img", food.getImg());
        values.put("desc", food.getDesc());
        values.put("price", food.getPrice());
        values.put("count", food.getCount());
        long result = db.insert("food", null, values);
        if (result == -1) {
            return new BusinessResult<>(false, "添加失败", null);
        }
        return new BusinessResult<>(true, "添加成功", food);
    }

    /**
     * 更新
     */
    private static BusinessResult<Food> update(Food food) {
        if (food.getUserId() == null) {
            return new BusinessResult<>(false, "用户id不能为空", null);
        }
        if (TextUtils.isEmpty(food.getName())) {
            return new BusinessResult<>(false, "食物名不能为空", null);
        }
        DatabaseHelper instance = DatabaseHelper.getInstance();
        SQLiteDatabase db = instance.getWritableDatabase();
        String sql = "UPDATE food SET img=?,'desc'=?,price=?,count=? WHERE name=? AND user_id=?";
        String[] args = new String[]{food.getImg(), food.getDesc(), String.valueOf(food.getPrice()), String.valueOf(food.getCount()), food.getName(), String.valueOf(food.getUserId())};
        db.execSQL(sql, args);
        return new BusinessResult<>(true, "更新成功", food);
    }

    /**
     * 根据Food的name和userId查询
     */
    public static BusinessResult<Food> queryByNameAndUserId(String name, Integer userId) {
        if (TextUtils.isEmpty(name)) {
            return new BusinessResult<>(false, "食物名不能为空", null);
        }
        if (userId == null) {
            return new BusinessResult<>(false, "用户id不能为空", null);
        }
        DatabaseHelper instance = DatabaseHelper.getInstance();
        SQLiteDatabase db = instance.getReadableDatabase();
        String sql = "SELECT * FROM food WHERE name=? AND user_id=?";
        String[] args = new String[]{name, String.valueOf(userId)};
        Food result = null;
        try (Cursor cursor = db.rawQuery(sql, args)) {
            if (cursor.moveToNext()) {
                result = new Food();
                result.setUserId(cursor.getInt(1));
                result.setName(cursor.getString(2));
                result.setImg(cursor.getString(3));
                result.setDesc(cursor.getString(4));
                result.setPrice(cursor.getFloat(5));
                result.setCount(cursor.getInt(6));
            }
        }
        if (result == null) {
            return new BusinessResult<>(false, "食物不存在", null);
        }
        return new BusinessResult<>(true, "食物已存在", result);
    }

    public static BusinessResult<List<Food>> queryByUserId(Integer userId) {
        if (userId == null) {
            return null;
        }
        DatabaseHelper instance = DatabaseHelper.getInstance();
        SQLiteDatabase db = instance.getReadableDatabase();
        String sql = "SELECT * FROM food WHERE user_id=?";
        String[] args = new String[]{String.valueOf(userId)};
        List<Food> result = new ArrayList<>();
        try (Cursor cursor = db.rawQuery(sql, args)) {
            while (cursor.moveToNext()) {
                Food food = new Food();
                food.setUserId(cursor.getInt(1));
                food.setName(cursor.getString(2));
                food.setImg(cursor.getString(3));
                food.setDesc(cursor.getString(4));
                food.setPrice(cursor.getFloat(5));
                food.setCount(cursor.getInt(6));
                result.add(food);
            }
        }
        return new BusinessResult<>(true, "查询成功", result);
    }

    public static void deleteByUserId(Integer userId) {
        if (userId == null) {
            return;
        }
        DatabaseHelper instance = DatabaseHelper.getInstance();
        SQLiteDatabase db = instance.getWritableDatabase();
        String sql = "DELETE FROM food WHERE user_id=?";
        String[] args = new String[]{String.valueOf(userId)};
        db.execSQL(sql, args);
    }
}
